package com.qijian.framework.aspectj;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.google.common.collect.Lists;
import com.qijian.common.annotation.JoinField;
import com.qijian.common.annotation.Log;
import com.qijian.common.core.domain.BaseEntity;
import com.qijian.common.core.domain.model.LoginUser;
import com.qijian.common.enums.BusinessStatus;
import com.qijian.common.enums.HttpMethod;
import com.qijian.common.utils.SecurityUtils;
import com.qijian.common.utils.ServletUtils;
import com.qijian.common.utils.StringUtils;
import com.qijian.common.utils.ip.IpUtils;
import com.qijian.common.utils.reflect.ReflectUtils;
import com.qijian.framework.manager.AsyncManager;
import com.qijian.framework.manager.factory.AsyncFactory;
import com.qijian.system.domain.SysOperLog;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;

import static com.qijian.common.utils.mybatis.WhereEntityTool.camelToUnderline;

/**
 * 操作日志记录处理
 *
 * @author qijian
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    private static final List<String> FILTER_PARAM_KEY;

    private static final SimplePropertyPreFilter filter = new SimplePropertyPreFilter();

    static {
        //系统字段过滤,节省空间
        filter.getExcludes().add("createBy");
        filter.getExcludes().add("createTime");
        filter.getExcludes().add("updateBy");
        filter.getExcludes().add("updateTime");

        FILTER_PARAM_KEY = Arrays.asList("ids", "number");
    }


    @Autowired
    private HttpServletRequest request;

    // 配置织入点
    @Pointcut("@annotation(com.qijian.common.annotation.Log)")
    public void logPointCut() {
    }

//    /**
//     * 处理完请求后执行
//     *
//     * @param joinPoint 切点
//     */
//    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
//    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
//        handleLog(joinPoint, null, jsonResult);
//    }

    @Around("logPointCut()")
    public Object doAroundReturning(ProceedingJoinPoint point) throws Throwable {
        String oldData = getOldData(point);
        Object result = point.proceed();
        handleLog(point, null, result, oldData);
        return result;
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        handleLog(joinPoint, e, jsonResult, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult, String oldData) {
        try {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            // 获取当前的用户
            String userName = "系统";
            Long userId = null;
            try {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                userName = loginUser.getUser().getNickName();
                userId = loginUser.getUserId();
            } catch (Exception ignored) {
            }

            // *========数据库日志=========*//
            SysOperLog operLog = new SysOperLog();
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            // 请求的地址
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            operLog.setOperIp(ip);

            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
            operLog.setOperName(userName);
            operLog.setOperUserId(userId);

            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
            operLog.setBeforeParam(oldData);
            // 保存数据库
            AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log     日志
     * @param operLog 操作日志
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception {
        // 设置action动作
        operLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType().ordinal());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog);
        }
        // 是否需要保存response，参数和值
        if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) {
            operLog.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
        }

    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) {
        String requestMethod = operLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            String cruxInfo = filterCruxInfo(joinPoint.getArgs());
//            operLog.setOperParam(StringUtils.substring(params, 0, 2000));
            operLog.setOperParam(params);
            operLog.setCruxInfo(cruxInfo);
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
                    try {
//                        Object jsonObj = JSON.toJSON(o);
////                        params += jsonObj.toString() + " ";
//                        params.append(jsonObj.toString()).append(" ");
                        //数据过长，过滤部分不需要的字段
                        params.append(JSON.toJSONString(o, filter)).append(" ");
                    } catch (Exception ignored) {
                    }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 过滤出来每个实体类内的的关键信息
     *
     * @param paramsArray 参数
     * @return 关键信息
     */
    private String filterCruxInfo(Object[] paramsArray) {
        if (paramsArray.length != 0) {
            List<Map<String, Object>> data = new ArrayList<>();
            for (Object obj : paramsArray) {
                if (obj == null || isFilterObject(obj)) {
                    continue;
                }
                Field idField = ReflectUtils.findObjectIdField(obj.getClass());
                List<Field> fields = Lists.newArrayList(ReflectUtil.getFields(obj.getClass(), d -> FILTER_PARAM_KEY.contains(d.getName())));
                if (idField != null) {
                    fields.add(idField);
                }
                if (CollectionUtil.isNotEmpty(fields)) {
                    Map<String, Object> collect = new HashMap<>();
                    fields.forEach(f -> {
                        Object val = ReflectUtil.getFieldValue(obj, f);
                        if (val != null) {
                            collect.put(f.getName(), val);
                        }
                    });
                    data.add(collect);
                }
            }
            return JSONUtil.toJsonStr(data);
        }
        return null;
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }

    private String getOldData(ProceedingJoinPoint point) throws Exception {
        if ("PUT".equals(request.getMethod())) {
            StringBuilder builder = new StringBuilder();
            Object[] args = point.getArgs();
            for (Object arg : args) {
                builder.append(getOldData(arg));
            }

            return builder.toString();
        }
        return null;
    }

    private String getOldData(Object obj) throws Exception {
        StringBuilder builder = new StringBuilder();
        if (obj instanceof Model) {
            List<Field> joinFields = new LinkedList<>();
            List<Object> objects = new LinkedList<>();
            List<Field> fields = getFields(obj);
            for (Field field : fields) {
                field.setAccessible(true);
                Object val = field.get(obj);
                if (ObjectUtils.isEmpty(val))
                    continue;
                //检测是否存在实体类属性，递归
                if (field.getType().equals(List.class)) {
                    List list = (List) val;
                    if (list.size() > 0) {
                        Type type = field.getGenericType();
                        if (type instanceof ParameterizedType) {
                            ParameterizedType pt = (ParameterizedType) type;
                            Class<?> actualTypeArgument = (Class<?>) pt.getActualTypeArguments()[0];
                            Object ins = actualTypeArgument.newInstance();
                            if (ins instanceof Model) {
                                List<Field> fieldList = getFields(ins);
                                for (Field value : fieldList) {
                                    JoinField joinFieldAnn = value.getAnnotation(JoinField.class);
                                    if (joinFieldAnn != null && joinFieldAnn.value()) {
                                        joinFields.add(value);
                                        objects.add(ins);
                                        break;
                                    }
                                }
                            }
                        }

                    }

                } else {
                    builder.append(getOldData(val));
                }
                //检测是否存在主键
                TableId tableId = field.getAnnotation(TableId.class);
                if (tableId != null || field.getName().equals("id")) {
                    Model model = (Model) obj;
                    Object oldData = model.selectById();
                    builder.append(JSONObject.toJSONString(oldData, filter));
                    for (int j = 0; j < joinFields.size(); j++) {
                        Field f = joinFields.get(j);
                        String column;
                        TableField tableField = f.getAnnotation(TableField.class);
                        if (tableField != null && tableField.value() != null) {
                            column = tableField.value();
                        } else {
                            column = camelToUnderline(f.getName());
                        }
                        QueryWrapper queryWrapper = new QueryWrapper();
                        queryWrapper.eq(column, field.get(obj));


                        Object o = objects.get(j);
                        List<Field> fieldList = getFields(o, null);
                        //判断是否有idDel字段
                        for (Field temp : fieldList) {
                            if (temp.getName().equals("isDel")) {
                                TableField tf = temp.getAnnotation(TableField.class);
                                if (tf == null || tf.exist()) {
                                    queryWrapper.eq("is_del", 0);
                                }
                                break;
                            }
                        }

                        Model m = (Model) o;
                        List list = m.selectList(queryWrapper);
                        builder.append(JSONArray.toJSONString(list, filter));
                    }
                    break;
                }
            }
            return builder.toString();
        }
        return "";
    }

    /**
     * 获取obj对象所有的Field(包括父类)
     *
     * @return /
     */
    public static List<Field> getFields(Object obj) {
        return getFields(obj, BaseEntity.class);
    }

    public static List<Field> getFields(Object obj, Class excludeClass) {
        List<Field> result = new ArrayList<>();
        Field[] second;
        for (Class<?> superClass = obj.getClass();
             superClass != Object.class && (excludeClass == null || superClass != excludeClass);
             superClass = superClass.getSuperclass()) {
            second = superClass.getDeclaredFields();
            result.addAll(Arrays.asList(second));
        }
        return result;
    }

    private String compareObjectVal(Object obj, Object oldObj) throws IllegalAccessException {
        Map map = new HashMap();
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            Object val = field.get(obj);
            if (val == null)
                continue;
            Object oldVal = field.get(oldObj);
            if (!val.equals(oldVal)) {
                map.put(field.getName(), oldVal);
            }
        }
        return JSONObject.toJSONString(map);
    }
}
